#pragma once

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <mutex>
#include <cassert>
#include <cassert>
#include <jsoncpp/json/json.h>
#include <algorithm>
#include "../comm/log.hpp"
#include "../comm/util.hpp"
#include "../comm/httplib.h"
#include "oj_view.hpp"
#include "oj_model.hpp"

namespace ns_control
{
    using namespace ns_model;
    using namespace ns_log;
    using namespace ns_util;
    using namespace std;
    using namespace ns_view;
    using namespace httplib;

    class Machine
    {
    public:
        int _port;      // 端口号
        string _ip;     // IP地址
        mutex *mtx;     // c++的mutex禁止拷贝，使用指针
        uint64_t _load; // 编译服务的负载

    public:
        Machine() : _port(0), _ip(""), mtx(nullptr), _load(0)
        {
        }
        ~Machine()
        {
        }
        void IncLoad()
        {

            if (mtx)
                mtx->lock();
            ++_load;
            if (mtx)
                mtx->unlock();
        }
        void ResetLoad()
        {
            if (mtx)
                mtx->lock();
            _load = 0;
            if (mtx)
                mtx->unlock();
        }
        void DecLoad()
        {
            if (mtx)
                mtx->lock();
            --_load;
            if (mtx)
                mtx->unlock();
        }
        uint64_t Load()
        {
            uint64_t __load = 0;
            if (mtx)
                mtx->lock();
            __load = _load;
            if (mtx)
                mtx->unlock();
            return _load;
        }
    };

    const string service_machine = "./conf/service_machine.conf";
    // 负载均衡模块
    class LoadBlance
    {
    private:
        // 提供编译服务的所有主机
        // 用下标充当编号
        vector<Machine> machines;

        // 所有在线主机id
        vector<int> online;
        // 所有离线主机id
        vector<int> offline;

        // 保证LoadBlance的数据安全
        mutex mtx;

    public:
        LoadBlance()
        {
            assert(LoadConf(service_machine));
            LOG(INFO) << "加载 " << service_machine << " 成功" << "\n";
        }
        ~LoadBlance()
        {
        }

    public:
        bool LoadConf(const string &machine_conf)
        {
            ifstream in(machine_conf);
            if (!in.is_open())
            {
                LOG(FATAL) << "加载: " << machine_conf << "失败" << "\n";
                return false;
            }
            string line;
            while (getline(in, line))
            {
                vector<string> tokens;
                StringUtil::SplitString(line, &tokens, ":");
                if (tokens.size() != 2)
                {
                    LOG(WARNING) << "切分 " << line << " 失败" << "\n";
                    continue;
                }
                Machine m;
                m._port = (atoi(tokens[1].c_str()));
                m._ip = (tokens[0]);
                m._load = 0;
                m.mtx = new mutex();

                online.push_back(machines.size());
                machines.push_back(m);
            }
            in.close();
            return true;
        }
        // id:输出型参数
        // m: 输出型参数
        bool SmartChoice(int *id, Machine **m)
        {
            // 1.使用选择好的主机
            // 2.可能需要离线该主机
            mtx.lock();

            // 负载均衡的算法
            // 1.随机数+hash
            // 2.轮询+hash
            int online_number = online.size();
            if (online_number == 0)
            {
                mtx.unlock();
                LOG(FATAL) << "所有的后台编译主机都已经离线" << "\n";
                return false;
            }

            // 通过遍历找到负载最低的主机
            *id = online[0];
            *m = &machines[online[0]];
            uint64_t min_load = machines[online[0]].Load();
            for (int i = 1; i < online_number; i++)
            {
                uint64_t cur_load = machines[online[i]].Load();
                if (min_load > cur_load)
                {
                    *m = &machines[online[i]];
                    *id = online[i];
                    min_load = machines[online[i]].Load();
                }
            }

            mtx.unlock();
            return true;
        }
        void OnlineMachine()
        {
            mtx.lock();
            online.insert(online.end(), offline.begin(), offline.end());
            offline.erase(offline.begin(), offline.end());
            mtx.unlock();
            LOG(INFO) << "所有的主机又上线啦!........ " << "\n";
        }
        void OfflineMachine(int which)
        {
            mtx.lock();
            for (auto res = online.begin(); res != online.end(); res++)
            {
                if (*res == which)
                {
                    machines[which].ResetLoad();
                    online.erase(res);
                    offline.push_back(which);
                    break;
                }
            }
            mtx.unlock();
        }

        void ShowMachines()
        {
            mtx.lock();
            cout << "当前在线的主机列表: ";
            for (auto &iter : online)
            {
                cout << iter << " ";
            }
            cout << endl;

            cout << "当前离线的主机列表: ";
            for (auto &iter : offline)
            {
                cout << iter << " ";
            }
            cout << endl;
            mtx.unlock();
        }
    };

    // 这是核心业务逻辑的控制器
    class Control
    {
    private:
        Model _model;
        View _view;
        LoadBlance _load_blance; // 核心负载均衡器
    public:
        Control()
        {
        }
        ~Control()
        {
        }

        void RecoveryMachine()
        {
            _load_blance.OnlineMachine();
        }
        // 根据题目数据构建网页
        bool AllQuestions(string *html)
        {
            bool ret = true;
            vector<Question> all;
            if (_model.GetAllQuestions(&all))
            {
                sort(all.begin(), all.end(), [](const Question &q1, const Question &q2)
                     { return atoi(q1.number.c_str()) < atoi(q2.number.c_str()); });
                // 获取题目成功,将所有的题目数据改建成网页
                _view.AllExpandHtml(all, html);
            }
            else
            {
                *html = "获取题目失败，形成题目列表失败";
                ret = false;
            }
            return ret;
        }
        bool Questions(const string &number, string *html)
        {
            bool ret = true;
            Question q;
            if (_model.GetOneQuestion(number, &q))
            {
                // 获取题目成功,将题目数据构建成网页
                _view.OneExpandHtml(q, html);
            }
            else
            {
                *html = "指定题目：" + number + "不存在";
                ret = false;
            }
            return ret;
        }

        // id: 100
        // code: "#include.."
        // input:""
        void Judge(const string &number, const string &in_json, string *out_json)
        {

            // 0.根据题目编号，拿到对应的细节
            Question q;
            _model.GetOneQuestion(number, &q);

            // 1.对json串进行反序列化,得到id以及用户提交的代码
            Json::Reader reader;
            Json::Value in_value;
            reader.parse(in_json, in_value); // 将in_json解析成in_value
            string code = in_value["code"].asString();

            // 2.重新拼接用户的代码+测试用例代码，形成新的代码
            Json::Value compile_value;
            compile_value["input"] = in_value["input"].asString();
            compile_value["code"] = code + q.tail;
            compile_value["cpu_limit"] = q.cpu_limit;
            compile_value["mem_limit"] = q.mem_limit;

            Json::FastWriter writer;
            string compile_string = writer.write(compile_value);

            // 3.选择负载最低的主机（差错处理）
            // 规则：一直选择，直到主机可用，否则代表机器全部挂掉
            while (true)
            {
                int id = 0;
                Machine *m = nullptr;
                if (!_load_blance.SmartChoice(&id, &m))
                {
                    break;
                }
                // 4.发起http请求，得到判题结果
                Client cli(m->_ip, m->_port);
                m->IncLoad();
                LOG(INFO) << "选择主机成功,主机id: " << id << " 详情: " << m->_ip << ":" << m->_port << " 当前主机的负载是: " << m->Load() << "\n";
                if (auto res = cli.Post("/compile_and_run", compile_string, "application/json;charset=utf-8"))
                {
                    // 5.将结果给out_json
                    if (res->status == 200)
                    {
                        *out_json = res->body;
                        m->DecLoad();
                        LOG(INFO) << "请求编译运行服务成功...." << "\n";
                        break;
                    }
                    m->DecLoad();
                }
                else
                {
                    // 请求失败
                    LOG(ERROR) << "当前请求的主机id: " << id << " 详情: " << m->_ip << ":" << m->_port << " 可能已经挂掉" << "\n";
                    _load_blance.OfflineMachine(id);
                    _load_blance.ShowMachines();
                }
            }
        }
    };
}